<?php

namespace plugins\module_config\controller;



use app\common\lib\user_operate\ModuleOperate as MO; //引入此类

use cmf\controller\PluginAdminBaseController;

use plugins\module_config\model\PluginApiIndexModel as Model;



/**

 * 数据表配置管理控制器

 */

class TableConfigController extends PluginAdminBaseController

{

    protected function _initialize()

    {

        parent::_initialize();

        $this->Model = new Model();

        $adminId     = cmf_get_current_admin_id(); //获取后台管理员id，可判断是否登录

        if (!empty($adminId)) {

            $this->assign("admin_id", $adminId);

        }

    }

    /**

     * 首页

     */

    public function index()

    {

        $data = $this->request->param();

        if (!empty($data['name_storeid'])) {

            $name_storeid     = $data['name_storeid'];

            $data['name']     = explode('|', $name_storeid)[0];

            $data['store_id'] = explode('|', $name_storeid)[1];

        }

        //模块列表

        $mo          = new MO();

        $module_list = $mo->getModuleList();

        if ($module_list['status'] != 'success') {

            $list = [];

        } else {

            $list = $module_list['data'];

        }

        $this->assign('module_list', $list);

        //模块配置文件列表

        $file_list = $this->Model->getModuleTags($data['name']);

        $this->assign('file_list', $file_list);

        //模块内容

        if (!empty($data['file_name'])) {

            $file_content = $this->Model->getModuleTags($data['name'], $data['file_name']);

        } else {

            if (!empty($file_list)) {

                $file_content = $this->Model->getModuleTags($data['name'], $file_list[0]);

            } else {

                $file_content = [];

            }

        }

        \think\Hook::add('addTagsHtml', 'plugins\\module_config\\common\\AddTagsHtml');

        $this->assign('file_content', $file_content);

        //控件类型

        $tags      = $this->Model->getTagsConfig();

        $ctrl_type = $tags['ctrl_type'];

        $this->assign('ctrl_type', $ctrl_type);

        $input_type = $tags['input_type'];

        $this->assign('input_type', $input_type);

        //获取html配置

        $html = $this->getHtmlConfig($data['name']);

        $this->assign('html', $html);

        $data['file_name'] = !empty($data['file_name']) ? $data['file_name'] : '';

        $this->assign('view', $this);

        $this->assign('data', $data);

        return $this->fetch();

    }

    /**

     * 获取html配置

     */

    public function getHtmlConfig($module_name = '')

    {

        $res = getModuleConfig($module_name, 'config', 'html.json');

        $res = json_decode($res, true);

        if (!empty($res['html'])) {

            return $res['html'];

        }

        return $res;

    }

    /**

     * 需要引入的文件标签名

     */

    public function keyTags($module_name, $file_name)

    {

        $file_content = $this->Model->getModuleTags($module_name, $file_name);

        $keys         = [];

        if (!empty($file_content)) {

            $keys = array_keys($file_content);

        }

        return $keys;

    }

    /**

     * 获取文件配置

     */

    public function getConfig($tag)

    {

        $data = $this->request->param();

        if (!empty($data['name_storeid'])) {

            $name_storeid     = $data['name_storeid'];

            $data['name']     = explode('|', $name_storeid)[0];

            $data['store_id'] = explode('|', $name_storeid)[1];

        }

        if (empty($data['file_name'])) {

            return $this->success('success', '', []);

        }
        //得到配置
        $config = $this->Model->getModuleTags($data['name'], $data['file_name']);
        $list        = $config[$tag];
        $list        = !empty($list) ? $list['fields'] : [];
        if(!empty($config[$data['tag']]['database'])){
            $table_field = $this->Model->getMainTable($config[$data['tag']]['database']);
        }else{
            $table_field = $this->Model->getMainTable($data['name']);
        }
        //检查是否是主表字段

        foreach ($list as $key => $value) {

            if (empty($value['field'])) {

                continue;

            }

            if (in_array($value['field'], $table_field)) {

                //属于表中字段

                $value['is_table'] = 1;

            } else {

                $value['is_table'] = 0;

            }

            $list[$key] = $value;

        }

        return $this->success('success', '', $list);

    }

    /**

     * 更新显示字段

     */

    public function update()

    {

        $data = $this->request->param();
        if (!empty($data['name_storeid'])) {

            $name_storeid     = $data['name_storeid'];

            $data['name']     = explode('|', $name_storeid)[0];

            $data['store_id'] = explode('|', $name_storeid)[1];

        }

        $tg = $data['tag'];

        //获取配置
        $tags = $this->Model->getModuleTags($data['name'], $data['file_name']);

        //1.列出表中字段
        //有配置额外数据库的情况
        if(!empty($tags[$data['tag']]['database'])){
            $table_field = $this->Model->getMainTable($tags[$data['tag']]['database']);
        }else{
            $table_field = $this->Model->getMainTable($data['name']);
        }
        
        if (empty($table_field)) {
            return $this->error('主表不存在');
        }


        //2.获取配置文件
        //获取已经配置了字段列表

        $ziduan = !empty($tags[$tg]['fields']) ? array_keys($tags[$tg]['fields']) : [];

        foreach ($table_field as $key => $value) {

            if (in_array($value, $ziduan)) {

                continue;

            }

            switch ($tg) {

                case 'table':

                    $tags['table']['fields'][$value] =

                        [

                        'sort'         => '',

                        'title'        => '',

                        'field'        => $value,

                        'alias'        => '',

                        'is_show'      => '',

                        'show_type'    => '1',

                        'option'       => '',

                        'rule'         => '',

                        'is_relevance' => '',

                        'default'      => '',

                        'permission'    =>  ''

                    ];

                    break;

                case 'add':

                    $tags['add']['fields'][$value] =

                        [

                        'title'       => '',

                        'sort'        => '',

                        'placeholder' => '',

                        'field'       => $value,

                        'html'        => '',

                        'ctrl_type'   => '',

                        'placeholder' => '',

                        'is_show'     => '',

                        'show_type'   => '',

                        'is_sole'     => '',

                        'option'      => '',

                        'default'     => '',

                        'permission'  => ''

                    ];

                    break;

                case 'edit':

                    $tags['edit']['fields'][$value] =

                        [

                        'title'       => '',

                        'sort'        => '',

                        'placeholder' => '',

                        'field'       => $value,

                        'html'        => '',

                        'ctrl_type'   => '',

                        'placeholder' => '',

                        'is_show'     => '',

                        'show_type'   => '',

                        'is_sole'     => '',

                        'option'      => '',

                        'default'     => '',

                        'permission'  => ''

                    ];

                    break;

                case 'detail':

                    $tags['detail']['fields'][$value] =

                        [

                        'title'       => '',

                        'sort'        => '',

                        'placeholder' => '',

                        'field'       => $value,

                        'html'        => '',

                        'ctrl_type'   => '',

                        'placeholder' => '',

                        'is_show'     => '',

                        'show_type'   => '',

                        'option'      => '',

                        'default'     => '',
                        'permission'  => ''

                    ];

                    break;

                default:

                    # code...

                    break;

            }

        }
        //写入文件

        $save = $this->Model->saveTags($data['name'], $data['file_name'], $tags);

        if ($save) {

            $this->success('更新成功');

        } else {

            $this->error('更新失败');

        }

    }

    /**

     * 根据模块名取出文件名

     */

    public function getFileName()

    {

        $data        = $this->request->param();

        $module_name = $data['module_name'];

        $module_name = explode('|', $module_name)[0];

        $file_list   = $this->Model->getModuleTags($module_name);

        return $this->success('success', '', $file_list);

    }

    /**

     * 保存模块配置

     */

    public function saveConfig()

    {

        $data = $this->request->param();

        if (!empty($data['name_storeid'])) {

            $name_storeid     = $data['name_storeid'];

            $data['name']     = explode('|', $name_storeid)[0];

            $data['store_id'] = explode('|', $name_storeid)[1];

        }

        if (empty($data['form'])) {

            $this->error('提交内容不能为空');

        }



        //1.取出原来所有的值

        $tags = $this->Model->getModuleTags($data['name'], $data['file_name']);

        $form = $data['form'];

        $form = autoHtmlspecialcharsDecode($form);

        $tg   = $this->keyTags($data['name'], $data['file_name']);



        foreach ($tg as $key => $value) {

            switch ($value) {

                case 'search':

                    $tags['search']['fields'] = !empty($form['search']) ? array_column($form['search']['fields'], null, 'ctrl_name') : [];

                    unset($tags['search']['fields']['']);

                    break;

                case 'table':

                    $tags['table']['fields'] = !empty($form['table']) ? array_column($form['table']['fields'], null, 'field') : [];

                    unset($tags['table']['fields']['']);

                    break;

                case 'add':

                    $tags['add']['fields'] = !empty($form['add']) ? array_column($form['add']['fields'], null, 'field') : [];

                    unset($tags['add']['fields']['']);

                    break;

                case 'edit':

                    $tags['edit']['fields'] = !empty($form['edit']) ? array_column($form['edit']['fields'], null, 'field') : [];

                    unset($tags['edit']['fields']['']);

                    break;

                case 'detail':

                    $tags['detail']['fields'] = !empty($form['detail']) ? array_column($form['detail']['fields'], null, 'field') : [];

                    unset($tags['detail']['fields']['']);

                    break;

            }

        }

//         [

        //         "cmf_member",

        //         "cmf_member_group",

        //         "cmf_member.group_id=cmf_member_group.group_id",

        // "left",

        //         {

        //           "group_name": "group_name"

        //         }

        //       ]

        $ctrl_name = !empty($tags['table']['fields']) ? array_keys($tags['table']['fields']) : [];

        $relevance = !empty($tags['table']['relevance']) ? array_keys($tags['table']['relevance']) : [];

        foreach ($relevance as $key => $value) {

            if (!in_array($value, $ctrl_name)) {

                unset($tags['table']['relevance'][$value]);

            } else {

                if ($tags['table']['fields'][$value]['is_relevance'] != 1) {

                    unset($tags['table']['relevance'][$value]);

                }

            }

        }

        if (empty($data['file_name'])) {

            $this->error('未选择文件保存位置');

        }



        // dump($tg);exit;



        //添加同步到修改

        if (in_array('add',$tg) && !empty($data['edit_file_name'])) {

            $edit['edit'] = $tags['add'];



            $this->Model->saveTags($data['name'], $data['edit_file_name'], $edit);

        }



        //写入文件

        $save = $this->Model->saveTags($data['name'], $data['file_name'], $tags);

        if ($save) {

            $this->success('保存成功');

        } else {

            $this->error('保存失败');

        }

    }

    /**

     * 渲染模板

     */

    public function excuteDisplay($var)

    {

        return $this->display($var);

    }

    /**

     * 检查json格式是否正确

     */

    public function checkJson()

    {

        $data = $this->request->param();

        $data = autoHtmlspecialcharsDecode($data);

        $val  = json_decode($data['val'], true);

        if (!is_array($val) || empty($val)) {

            return $this->error('json格式不正确');

        }

        return $this->success('true');

    }

}

